package com.example.demo.controller;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import com.example.utils.FileUtil;

/**
 * 读取本地图片
 * 
 * @author xupx
 *
 */
@Controller
public class CommonController {

	/**
	 * @param request
	 * @param response
	 * @param path
	 *            绝对路径 路径不能为D:\\ 双\\，用D:/
	 */
	@RequestMapping("/getImgByPath")
	@ResponseBody
	public void getImgByPath(HttpServletRequest request, HttpServletResponse response, String path) {
		if (!StringUtils.isEmpty(path)
				&& (path.toLowerCase().endsWith(".jpg") || path.toLowerCase().endsWith(".png"))) {
			InputStream is = null;
			OutputStream os = null;
			try {
				File file = new File(path);
				if (!file.exists())
					return;
				else
					is = FileUtil.byte2Input(FileUtil.file2byte(path));
				os = response.getOutputStream();
				int count = 0;
				byte[] buffer = new byte[1024 * 1024];
				while ((count = is.read(buffer)) != -1) {
					os.write(buffer, 0, count);
					os.flush();
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (is != null) {
						is.close();
					}
					if (os != null) {
						os.close();
					}
					response.flushBuffer();
				} catch (Exception ex) {
					ex.printStackTrace();
				}

			}
		}
	}
}
